<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/3
 * Time: 10:30
 */

namespace api\modules\v1\controllers\member;

use addons\TfFutures\common\models\Symbol;
use addons\TfFutures\common\models\Order;
use addons\TfFutures\common\models\Logs;
use addons\TfFutures\common\models\Member;
use api\controllers\OnAuthController;
use common\helpers\ResultDataHelper;
use addons\TfFutures\services\OrderService;
use Yii;

class OverfeeController extends OnAuthController
{
    public $modelClass = '';
    //    protected $optional = ['add-pay'];
    protected $optional = ['overfee'];

    /*
     * 收取过夜费
     * */
    public function actionOverfee(){
        //先查询当前所有的产品
        $symbols = Symbol::find()->where(['status'=>1])->asArray()->all();
        if (empty($symbols)) {
            return ResultDataHelper::api(200,'当前没有产品');
        }
        foreach ($symbols as $ke => $symbol) {
            //todo 判断当前时间是否到了该产品收取过夜费的时间

            $where['state'] = '持仓';
            $where['symbol'] =$symbol['code2'];
            $order = Order::find()->where($where)->asArray()->all();
            if(empty($order)){
                continue;
            }
            foreach ($order as $k => $v){
                $res = Member::find()->where(['member_id'=>$v['member_id']])->one();
                //计算过夜费
                $over_fee = $symbol['overfee'];

                $loadStatics = OrderService::loadStatic($v['member_id'],$res->price);
                //计算用户可用余额
                $deposits = $res->price - ($loadStatics['order_deposit'] + $loadStatics['reason_deposit']);
                if($deposits < $over_fee){
                    $aa = self::actionCloseAll($v['member_id']);
                }else{
                    $res->price = bcsub($res->price,$over_fee,4);
                    $res->save();
                    $order = Order::findOne($v['id']);
                    $order->overfee = bcsub($order->overfee,$over_fee,4);
                    $order->save();
                    Logs::addLogs($v['member_id'], '过夜费',$over_fee,bcadd($res->price, $over_fee, 4), $res->price, '持仓订单扣除过夜费'.$over_fee);
                }


            }
        }
        return ResultDataHelper::api(200,'过夜费收取成功');
    }
}